package com.xl.utils.util.redissonlock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author xionglin
 * @date 2021/5/15 20:40
 * @Description 测试redis的客户端redisson实现分布式锁
 */
public class RedissonlockTestDemo {


    //获取连接
    public static RedissonClient getRedissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("Xdx201811").setDatabase(0);
        return Redisson.create(config);
    }


    public static void main(String[] args) {
        test();
    }

    public static void test() {
        RedissonClient redissonClient = getRedissonClient();
        RLock rlock = redissonClient.getLock("xl-lock");
        //尝试取锁，有效期为3s，到期后自动释放。如果取得锁继续执行。取锁失败则自旋。
        rlock.lock(3, TimeUnit.SECONDS);
        System.out.println(Thread.currentThread().getName() + "取得锁");
        //h获取库存
        try {
            int store = 1;
            if (store > 0) {
                System.out.println("当前库存为："+store);
            } else
                System.out.println("已售完，下次再来吧");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("业务完成，释放锁");
            //业务完成，释放锁
            rlock.unlock();
        }

    }

}
